package org.enhance.common.util.convert;

import org.apache.commons.lang3.StringUtils;
import org.enhance.common.model.bo.FormTimeField;
import org.enhance.common.util.Assertion;
import org.enhance.common.util.DateFormatUtil;

import java.util.Date;
import java.util.regex.Pattern;

/**
 * @author JiangGengchao
 * @classname FormDateFieldUtil
 * @description
 * @date 2021-10-20
 **/
public class FormDateFieldUtil {
	/** yyyy-MM-dd HH:mm:ss */
	public static final String PATTERN_DATETIME = "^([1-2][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9])\\s[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$";

    private FormDateFieldUtil() {
        throw new IllegalStateException("Constant class");
    }

    public static FormTimeField parse(String timeStr) {
        return parse(timeStr, "时间");
    }

    public static FormTimeField parse(String timeStr, String fieldName) {
        FormTimeField timeField = new FormTimeField();

        if (StringUtils.isNotEmpty(timeStr)) {
            String[] timeStrs = StringUtils.strip(timeStr, "[]").split(",");
            Assertion.isTrue(timeStrs.length == 2, fieldName + "条件格式不正确：" + timeStr);
            // 对时间格式进行校验
            String startTimeStr = timeStrs[0];
            String endTimeStr = timeStrs[1];

            Assertion.notEmpty(startTimeStr, "lack begin " +fieldName );
            Assertion.notEmpty(endTimeStr, "lack end " + fieldName);

            if(Pattern.matches(PATTERN_DATETIME, startTimeStr)) {
                Date startTime = DateFormatUtil.parseDatetime(startTimeStr);
                timeField.setStartTime(startTime);
            } else if(isMillisecondTimestamp(startTimeStr)){
                timeField.setStartTime(new Date(Long.parseLong(startTimeStr)));
            } else {
                Assertion.isTrue(false, fieldName + "开始时间格式错误：" + startTimeStr);
            }

            if(Pattern.matches(PATTERN_DATETIME, endTimeStr)) {
                Date endTime = DateFormatUtil.parseDatetime(endTimeStr);
                timeField.setEndTime(endTime);
            } else if(isMillisecondTimestamp(endTimeStr)){
                timeField.setEndTime(new Date(Long.parseLong(endTimeStr)));
            } else {
                Assertion.isTrue(false, fieldName + "结束时间格式错误：" + startTimeStr);
            }
        }
        return timeField;
    }

    public static boolean isMillisecondTimestamp(String str) {
        // 1. 检查是否为null或空字符串
        if (str == null || str.trim().isEmpty()) {
            return false;
        }

        // 2. 检查是否为纯数字
        if (!str.matches("\\d+")) {
            return false;
        }

        // 3. 检查长度是否为13位（毫秒级时间戳通常为13位）
        if (str.length() != 13) {
            return false;
        }

        // 4. 检查是否在合理的时间范围内（例如1970-2100年之间）
        try {
            long timestamp = Long.parseLong(str);
            // 1970-01-01 00:00:00的毫秒时间戳
            long minTimestamp = 0L;
            // 2100-01-01 00:00:00的毫秒时间戳
            long maxTimestamp = 4102444800000L;

            return timestamp >= minTimestamp && timestamp <= maxTimestamp;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}
